package org.classg.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.classg.edu.entity.Chapter;
import org.classg.edu.entity.Video;
import org.classg.edu.mapper.ChapterMapper;
import org.classg.edu.service.ChapterService;
import org.classg.edu.service.VideoService;
import org.classg.edu.vo.ChapterVo;
import org.classg.edu.vo.VideoVo;
import org.classg.servicebase.exception.MyException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-05-18
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Autowired
    private VideoService videoService;

    // 根据课程id查询章节和小节信息
    @Override
    public List<ChapterVo> queryChapterAndVideoByCourseId(String courseId) {
        // 根据课程id查询章节
        List<Chapter> chapters = baseMapper.selectList(new LambdaQueryWrapper<Chapter>().eq(Chapter::getCourseId, courseId));
        // 根据课程id查询小节
        List<Video> videos = videoService.list(new LambdaQueryWrapper<Video>().eq(Video::getCourseId, courseId));
        ArrayList<ChapterVo> finalList = new ArrayList<>();
        for (Chapter chapter : chapters) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter, chapterVo);
            ArrayList<VideoVo> videoVos = new ArrayList<>();
            for (Video video : videos) {
                if (video.getChapterId().equals(chapter.getId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video, videoVo);
                    videoVos.add(videoVo);
                    chapterVo.setChildren(videoVos);
                }
            }
            finalList.add(chapterVo);
        }
        return finalList;
    }

    // 根据id删除章节
    @Override
    public Boolean deleteChapterById(String id) {
        // 根据章节id查询所有关于的小节
        int temp = videoService.count(new LambdaQueryWrapper<Video>().eq(Video::getChapterId, id));
        // 判断
        if (temp > 0) {
            // 有小节
            throw new MyException(20001, "章节内有小节，无法删除");
        } else {
            // 没有小节
            int result = baseMapper.deleteById(id);
            return result > 0;
        }
    }

    // 根据课程id删除章节
    @Override
    public void deleteChapterByCourseId(String id) {
        baseMapper.delete(new LambdaQueryWrapper<Chapter>().eq(Chapter::getCourseId, id));
    }
}
